<?php 
namespace Material\Controller;
use Qiniu;
use Think\Controller;
class MediaController extends Controller{
	
	public function uploader(){
		$this->display();
	}
	
	/**
	 * 视频列表
	 */
	public function videos(){
		$this->display();
	}
	
	/**
	 * 上传视频交互界面
	 */
	public function upload(){
		if($_GET['id']){
			$this->info = D('MaterialVideos')->relation(true)->find($_GET['id']);
		}
		$this->display();
	}
	
	public function upload_post(){
		if(IS_POST){
			$m = D('MaterialVideos');
			$_POST['update_time'] = Date('Y-m-d H:i:s');
			$data = $m->create($_POST);
			if($_POST['id']){
				if($m->save($data)){
					$ret = $m->find($_POST['id']);
					$ret['other'] = $_POST['other'];  //other参数表示返回给父页面的参数
					_apiReturn(1, "上传成功", $ret);
					$this->success("上传成功");
				}else{
					$this->error("上传失败");
				}
			}else{
				if(!I('key')){
					_apiReturn(0, "上传失败", $ret);
				}
				$data['uid'] = $_SESSION['loginUser']['uid']; //存储上传者ID
				if(!$data['uid']) $data['uid'] = 0;
				$id = $m->add($data);
				if($id){
					$ret = $m->find($id);
					$ret['other'] = $_POST['other'];
					_apiReturn(1, "添加成功", $ret);
				}else{
					$this->error("添加失败");
				}
			}
		}
	}
	
	public function findvideo(){
		$data = D('MaterialVideos','Logic')->get_video($_REQUEST['key']);
		if($data){
			_apiReturn(1, '', $data, $url);
		}else{
			_apiReturn(0, '找不到相应的视频', $data, $url);
		}
	}
	
	public function uptoken(){
		Vendor('Qiniu.Config');
		Vendor('Qiniu.functions');
		vendor('Qiniu.Auth');
		$config = C('QINIU_CONFIG');
		$accessKey = $config['accessKey'];
		$secretKey = $config['secretKey'];
		$auth = new \Qiniu\Auth($accessKey, $secretKey);
		
		$qiniu_config = C('QINIU_CONFIG');
		$bucket = $qiniu_config['bucket'];
		$upToken = $auth->uploadToken($bucket);
		$data['uptoken'] = $upToken;
		echo '{"uptoken":"'.$upToken.'"}';
		die();
		
	}
	
	public function del(){
		$m = D('MaterialVideos');
		$id = array_unique((array)I('ids',0));
		if ( empty($id) ) {
			$this->error('请选择要操作的数据!');
		}
		$map = array($m->getPk() => array('in', $id));
		$lists = $m->where($map)->select();
		//过滤非法操作
		if($_SESSION['loginUser']['role'] != 'ROLE_SUPER_ADMIN'){
			foreach($lists as $vo){
				if($_SESSION['loginUser']['uid'] != $vo['uid']){
					$this->error('您没有该操作权限！');
				}
			}
		}
		
		if($m->where($map)->delete()){ //删除本地数据库中的row
			foreach($lists as $vo){
				$config = C('QINIU_CONFIG');
				$qiniu = new \Think\Upload\Driver\Qiniu($config);
				$qiniu->del($vo['key']); //删除七牛远程图片
			}
			$this->success('删除成功');
		} else {
			$this->error('删除失败！');
		}
	}

}
?>